<template>
  <base-layout>
    <div class="project-problem-container">
      <!-- 左侧信息区域 -->
      <div class="info-section">
        <a-card class="info-card">
          <template #title>
            <div class="card-title">项目基本信息</div>
          </template>
          <div class="info-content">
            <div class="info-item">
              <span class="label">项目名称：</span>
              <span class="value">{{ project.name }}</span>
              <a-tag color="blue" class="course-tag">{{ project.course }}</a-tag>
            </div>
            <div class="info-item">
              <span class="label">开始日期：</span>
              <span class="value">{{ project.startDate }}</span>
            </div>
            <div class="info-item">
              <span class="label">组长：</span>
              <div class="value select-container">
                <a-select
                  v-model:value="project.leader"
                  style="width: 200px"
                  :options="userOptions"
                  placeholder="请选择组长"
                  :disabled="!isEditing"
                />
              </div>
            </div>
            <div class="info-item">
              <span class="label">组员：</span>
              <div class="value select-container">
                <a-select
                  v-model:value="project.members"
                  mode="multiple"
                  style="width: 100%"
                  :options="userOptions.filter(user => user.value !== project.leader)"
                  placeholder="请选择组员"
                  :disabled="!isEditing"
                  @change="handleMembersChange"
                />
              </div>
            </div>
            <div class="info-item description">
              <span class="label">项目描述：</span>
              <div class="value description-text">{{ project.description }}</div>
            </div>
          </div>
        </a-card>

        <!-- 进度卡片 -->
        <a-card class="progress-card">
          <template #title>
            <div class="card-title">项目进度</div>
          </template>
          <div class="progress-steps">
            <div v-for="(step, index) in progressSteps" :key="index" 
                 class="step-item" 
                 :class="{ active: index <= currentStep }">
              <div class="step-dot"></div>
              <div class="step-info">
                <div class="step-label">{{ step }}</div>
                <div class="step-date">{{ progressDates[index] || '-' }}</div>
                <div class="step-status">
                  <template v-if="stepSubmissions[index]">
                    <check-circle-filled class="status-icon success" />
                    <span class="status-text">已提交</span>
                  </template>
                  <template v-else>
                    <clock-circle-filled class="status-icon pending" />
                    <span class="status-text">未提交</span>
                  </template>
                </div>
              </div>
            </div>
          </div>
        </a-card>

        <!-- 历史提交记录卡片 -->
        <a-card class="history-card">
          <template #title>
            <div class="card-title">历史提交记录</div>
          </template>
          <a-timeline>
            <a-timeline-item v-for="(record, index) in submissionHistory" :key="index">
              <template #dot>
                <check-circle-outlined style="color: #52c41a" />
              </template>
              <div class="timeline-content">
                <div class="timeline-header">
                  <span class="timeline-title">{{ progressSteps[record.step] }}</span>
                  <span class="timeline-time">{{ record.time }}</span>
                </div>
                <div class="timeline-desc">{{ record.description }}</div>
                <div class="timeline-files">
                  <div v-for="(file, fileIndex) in record.files" :key="fileIndex" class="file-item">
                    <file-outlined class="file-icon" />
                    <span class="file-name">{{ file.name }}</span>
                    <div class="file-actions">
                      <eye-outlined class="preview-icon" @click="handleHistoryPreview(file)" />
                      <download-outlined class="download-icon" @click="handleHistoryDownload(file)" />
                    </div>
                  </div>
                </div>
              </div>
            </a-timeline-item>
          </a-timeline>
        </a-card>
      </div>

      <!-- 右侧提交区域 -->
      <div class="submit-section">
        <a-card class="submit-card">
          <template #title>
            <div class="card-title">
              {{ progressSteps[currentStep] }} - 提交
            </div>
          </template>
          <div class="upload-area">
            <!-- 添加描述输入框 -->
            <div class="description-input">
              <div class="input-label">
                提交描述
                <span class="required">*</span>
              </div>
              <a-textarea
                v-model:value="submitDescription"
                :rows="4"
                placeholder="请输入本次提交的说明，如：完成了哪些功能、解决了什么问题等"
                :maxLength="500"
                show-count
                :status="submitDescription.trim() ? '' : 'error'"
              />
              <div class="error-tip" v-if="showDescriptionError">
                请输入提交描述
              </div>
            </div>

            <div class="upload-box" @click="triggerUpload" @drop.prevent="handleDrop" @dragover.prevent>
              <upload-outlined class="upload-icon" />
              <p class="upload-text">点击或拖拽文件到此处上传</p>
              <p class="upload-hint">支持扩展名：.rar .zip .doc .docx .pdf .jpg...</p>
            </div>
            <input type="file" ref="fileInput" style="display: none" @change="handleFileChange" multiple />
            
            <!-- 文件列表 -->
            <div class="file-list" v-if="uploadedFiles.length > 0">
              <div v-for="(file, index) in uploadedFiles" :key="index" class="file-item">
                <file-outlined class="file-icon" />
                <span class="file-name">{{ file.name }}</span>
                <div class="file-actions">
                  <eye-outlined class="preview-icon" @click="handlePreview(file)" />
                  <delete-outlined class="delete-icon" @click="removeFile(index)" />
                </div>
              </div>
            </div>

            <!-- 预览弹窗 -->
            <a-modal
              v-model:visible="previewVisible"
              :title="previewFile?.name"
              :footer="null"
              width="800px"
              @cancel="closePreview"
            >
              <div class="preview-content">
                <!-- 图片预览 -->
                <img
                  v-if="isImageFile(previewFile)"
                  :src="previewUrl"
                  class="preview-image"
                  alt="预览图片"
                />
                <!-- PDF预览 -->
                <iframe
                  v-else-if="isPdfFile(previewFile)"
                  :src="previewUrl"
                  class="preview-pdf"
                ></iframe>
                <!-- 其他文件类型 -->
                <div v-else class="preview-unsupported">
                  <file-outlined class="unsupported-icon" />
                  <p>该文件类型暂不支持预览，请下载后查看</p>
                  <a-button type="primary" @click="downloadFile(previewFile)">
                    下载文件
                  </a-button>
                </div>
              </div>
            </a-modal>

            <div class="submit-actions">
              <a-button @click="handleClear">
                <template #icon><clear-outlined /></template>
                取消
              </a-button>
              <a-button type="primary" :loading="submitting" @click="handleSubmit">
                <template #icon><check-outlined /></template>
                提交
              </a-button>
            </div>
          </div>
        </a-card>
      </div>
    </div>
  </base-layout>
</template>

<script>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import BaseLayout from '@/components/layout/BaseLayout.vue'
import { 
  UploadOutlined, 
  FileOutlined, 
  DeleteOutlined,
  CheckOutlined,
  ClearOutlined,
  EyeOutlined,
  CheckCircleFilled,
  ClockCircleFilled
} from '@ant-design/icons-vue'

export default {
  name: 'ProjectProblem',
  components: {
    BaseLayout,
    UploadOutlined,
    FileOutlined,
    DeleteOutlined,
    CheckOutlined,
    ClearOutlined,
    EyeOutlined,
    CheckCircleFilled,
    ClockCircleFilled
  },
  setup() {
    const route = useRoute()
    const fileInput = ref(null)
    const uploadedFiles = ref([])
    const submitting = ref(false)
    const submitDescription = ref('')
    const showDescriptionError = ref(false)
    const previewVisible = ref(false)
    const previewFile = ref(null)
    const previewUrl = ref('')

    // 当前登录用户信息
    const currentUser = ref({
      id: '1',
      name: '当前用户',
      // 其他用户信息...
    })

    // 是否处于编辑状态
    const isEditing = ref(true)

    // 用户列表选项
    const userOptions = ref([
      { label: '当前用户', value: '1' },
      { label: '用户2', value: '2' },
      { label: '用户3', value: '3' },
      { label: '用户4', value: '4' },
      { label: '用户5', value: '5' },
    ])

    // 项目信息
    const project = ref({
      name: '示例项目',
      course: '示例课程',
      startDate: '2024-03-20',
      leader: currentUser.value.id, // 默认为当前用户
      members: [currentUser.value.id], // 默认包含当前用户
      description: '这是一个示例项目描述...'
    })

    // 进度步骤
    const progressSteps = ['项目目标及意义', '技术选型', '系统分析', '系统设计', '系统实现', '系统测试', '完成']
    const progressDates = ['2024-10-01 12:00']
    const currentStep = ref(0)

    // 模拟已提交的步骤
    const stepSubmissions = ref([true, true, false, false, false, false, false])

    // 模拟提交历史记录
    const submissionHistory = ref([
      {
        step: 0,
        time: '2024-03-15 14:30:00',
        description: '完成了项目目标分析和可行性研究',
        files: [
          {
            name: '项目目标分析报告.pdf',
            url: 'https://example.com/file1.pdf'
          }
        ]
      },
      {
        step: 1,
        time: '2024-03-16 16:20:00',
        description: '确定使用Vue3 + Spring Boot技术栈',
        files: [
          {
            name: '技术选型文档.docx',
            url: 'https://example.com/file2.docx'
          },
          {
            name: '技术调研报告.pdf',
            url: 'https://example.com/file3.pdf'
          }
        ]
      }
    ])

    const triggerUpload = () => {
      fileInput.value.click()
    }

    const handleFileChange = (e) => {
      const files = Array.from(e.target.files)
      uploadedFiles.value.push(...files)
    }

    const handleDrop = (e) => {
      const files = Array.from(e.dataTransfer.files)
      uploadedFiles.value.push(...files)
    }

    const removeFile = (index) => {
      uploadedFiles.value.splice(index, 1)
    }

    const handleClear = () => {
      uploadedFiles.value = []
      submitDescription.value = ''
      showDescriptionError.value = false
    }

    const handleSubmit = async () => {
      // 重置错误状态
      showDescriptionError.value = false

      // 验证描述是否填写
      if (!submitDescription.value.trim()) {
        showDescriptionError.value = true
        message.error('请输入提交描述')
        return
      }

      if (uploadedFiles.value.length === 0) {
        message.error('请先上传文件')
        return
      }

      submitting.value = true
      try {
        // 模拟提交请求
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        // 更新提交状态
        stepSubmissions.value[currentStep.value] = true
        
        // 添加到提交历史
        submissionHistory.value.unshift({
          step: currentStep.value,
          time: new Date().toLocaleString(),
          description: submitDescription.value,
          files: uploadedFiles.value.map(file => ({
            name: file.name,
            url: URL.createObjectURL(file)
          }))
        })

        message.success('提交成功')
        handleClear()
      } catch (error) {
        message.error('提交失败')
      } finally {
        submitting.value = false
      }
    }

    const isImageFile = (file) => {
      return file && /\.(jpg|jpeg|png|gif|webp)$/i.test(file.name)
    }

    const isPdfFile = (file) => {
      return file && /\.pdf$/i.test(file.name)
    }

    const handlePreview = async (file) => {
      previewFile.value = file
      
      if (isImageFile(file) || isPdfFile(file)) {
        previewUrl.value = URL.createObjectURL(file)
      }
      
      previewVisible.value = true
    }

    const closePreview = () => {
      previewVisible.value = false
      if (previewUrl.value) {
        URL.revokeObjectURL(previewUrl.value)
        previewUrl.value = ''
      }
      previewFile.value = null
    }

    const downloadFile = (file) => {
      const url = URL.createObjectURL(file)
      const a = document.createElement('a')
      a.href = url
      a.download = file.name
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    }

    // 处理历史文件预览
    const handleHistoryPreview = (file) => {
      previewFile.value = file
      previewVisible.value = true
    }

    // 处理历史文件下载
    const handleHistoryDownload = (file) => {
      const a = document.createElement('a')
      a.href = file.url
      a.download = file.name
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    }

    // 处理组员变化
    const handleMembersChange = (selectedMembers) => {
      // 确保组员中不包含组长
      project.value.members = selectedMembers.filter(
        memberId => memberId !== project.value.leader
      )
    }

    // 监听组长变化
    watch(() => project.value.leader, (newLeader, oldLeader) => {
      // 如果新组长在组员中，则从组员中移除
      if (project.value.members.includes(newLeader)) {
        project.value.members = project.value.members.filter(
          memberId => memberId !== newLeader
        )
      }
    })

    return {
      project,
      fileInput,
      uploadedFiles,
      submitting,
      progressSteps,
      progressDates,
      currentStep,
      stepSubmissions,
      submissionHistory,
      triggerUpload,
      handleFileChange,
      handleDrop,
      removeFile,
      handleClear,
      handleSubmit,
      submitDescription,
      showDescriptionError,
      previewVisible,
      previewFile,
      previewUrl,
      isImageFile,
      isPdfFile,
      handlePreview,
      closePreview,
      downloadFile,
      handleHistoryPreview,
      handleHistoryDownload,
      isEditing,
      userOptions,
      currentUser,
      handleMembersChange,
    }
  }
}
</script>

<style scoped>
.project-problem-container {
  padding: 24px;
  min-height: calc(100vh - 64px);
  background: #f0f2f5;
  display: flex;
  gap: 24px;
}

.info-section {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.submit-section {
  width: 480px;
  flex-shrink: 0;
}

.info-card,
.progress-card,
.history-card,
.submit-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
}

.info-card,
.progress-card,
.history-card {
  margin: 0;
}

.progress-card {
  padding: 24px;
}

.progress-card :deep(.ant-card-body) {
  padding: 0;
}

.progress-steps {
  display: flex;
  flex-direction: column;
  gap: 32px;
  padding: 24px 0;
}

.step-item {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  position: relative;
  padding-left: 16px;
}

.step-item::before {
  content: '';
  position: absolute;
  left: 7px;
  top: 24px;
  bottom: -32px;
  width: 2px;
  background: #e8e8e8;
}

.step-item:last-child::before {
  display: none;
}

.step-item.active::before {
  background: var(--primary-color);
}

.step-dot {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: #e8e8e8;
  margin-top: 4px;
  flex-shrink: 0;
}

.step-item.active .step-dot {
  background: var(--primary-color);
}

.step-label {
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
}

.step-date {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
  margin-top: 4px;
}

.submit-card {
  position: sticky;
  top: 24px;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  line-height: 24px;
}

.info-item .label {
  color: #8c8c8c;
  min-width: 80px;
}

.info-item .value {
  flex: 1;
}

.course-tag {
  margin-left: 8px;
}

.description {
  align-items: flex-start;
}

.description-text {
  white-space: pre-wrap;
  line-height: 1.6;
}

.upload-area {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
}

.description-input {
  margin-bottom: 16px;
}

.input-label {
  color: #262626;
  font-size: 14px;
  margin-bottom: 8px;
}

.required {
  color: #ff4d4f;
  margin-left: 4px;
  font-size: 14px;
}

.error-tip {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

.upload-box {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  padding: 32px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-box:hover {
  border-color: #40a9ff;
}

.upload-icon {
  font-size: 48px;
  color: #8c8c8c;
  margin-bottom: 16px;
}

.upload-text {
  color: #262626;
  margin-bottom: 8px;
}

.upload-hint {
  color: #8c8c8c;
  font-size: 12px;
}

.file-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: #fafafa;
  border-radius: 4px;
}

.file-icon {
  color: #8c8c8c;
  margin-right: 8px;
}

.file-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.preview-icon {
  color: #1890ff;
  cursor: pointer;
  padding: 4px;
}

.preview-icon:hover {
  color: #40a9ff;
}

.preview-content {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background: #f0f2f5;
  border-radius: 4px;
  padding: 16px;
}

.preview-image {
  max-width: 100%;
  max-height: 600px;
  object-fit: contain;
}

.preview-pdf {
  width: 100%;
  height: 600px;
  border: none;
}

.preview-unsupported {
  text-align: center;
  padding: 32px;
}

.unsupported-icon {
  font-size: 48px;
  color: #8c8c8c;
  margin-bottom: 16px;
}

.submit-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 16px;
}

@media screen and (max-width: 1200px) {
  .project-problem-container {
    flex-direction: column;
  }

  .submit-section {
    width: 100%;
  }

  .submit-card {
    position: static;
  }
}

:deep(.ant-input-status-error) {
  border-color: #ff4d4f;
}

:deep(.ant-input-status-error:hover) {
  border-color: #ff7875;
}

:deep(.ant-input-status-error:focus) {
  border-color: #ff7875;
  box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2);
}

:deep(.ant-modal-body) {
  padding: 0;
}

.select-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.ant-select) {
  width: 100%;
}

:deep(.ant-select-disabled) {
  opacity: 0.8;
}
</style> 